package com.reach.redis.interceptor;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

import org.aopalliance.intercept.MethodInvocation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.util.ReflectionUtils;

import com.reach.redis.annotation.CacheEvict;
import com.reach.redis.annotation.Cacheable;
import com.reach.redis.bo.CacheConfig;

 
/**
 * 缓存拦截
 */

public class CacheInterceptor extends AbstractCacheInterceptor {

	private static final Logger logger = LoggerFactory.getLogger(CacheInterceptor.class);
	
	public Object intercept(MethodInvocation invo) throws Throwable {
		try {
			Method[] methods = ReflectionUtils.getAllDeclaredMethods(invo.getThis().getClass());
			if (methods == null || methods.length <=0) {
				return invo.proceed();
			}
			for (Method method : methods) {
				if(method.getName().equals(invo.getMethod().getName())) {
					Annotation  cacheable = AnnotationUtils.findAnnotation(method,Cacheable.class);
					Annotation  cacheEvict = AnnotationUtils.findAnnotation(method,CacheEvict.class);
					CacheConfig cacheConfig = new CacheConfig();
					cacheConfig.setTargetMethod(invo.getMethod());
					cacheConfig.setTargetObject(invo.getThis());
					//cacheConfig.setBeanName(invo.getThis().get);
					if(cacheable != null) {
						cacheConfig.setCache(cacheable);
						return new QueryCacheInterceptor().intercept(invo,cacheConfig);
					}	
					
					if(cacheEvict != null) {
						cacheConfig.setCache(cacheEvict);
						return new ModificationCacheInterceptor().intercept(invo,cacheConfig);
					}	
				}
			}
		}catch(Exception e) {
			logger.error(e.getMessage());
		}
		return invo.proceed();
	}
		

	@Override
	public String[] getAnnotation(CacheConfig cacheConfig) {
		Cacheable cacheable = (Cacheable) cacheConfig.getCache();
		return getTrim(cacheable.key().split(","));
	}

	@Override
	public String getModule(CacheConfig cacheConfig) {
		return null;
	}

	@Override
	public String getEvent(CacheConfig cacheConfig) {
		return null;
	}


 
}